package com.tuanzi.loan.business.service.sms.el;

import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.service.sms.vo.SmsSearchResponse;

@Component
public abstract class AbstractEvaluator implements BackToRootEvaluator {

	@Autowired
	private EvaluateRoot evaluateRoot;

	protected static final Integer HANDLE_RECORD_PER_LOOP = 20000;

	protected List<String> getResponsePhoneIds(List<SmsSearchResponse> responses) {
		return responses.stream().map(SmsSearchResponse::getPhoneId).filter(StringUtils::isNotBlank).collect(Collectors.toList());
	}

	protected List<String> getResponsePhone(List<SmsSearchResponse> responses) {
		return responses.stream().map(SmsSearchResponse::getPhone).filter(StringUtils::isNotBlank).collect(Collectors.toList());
	}

	protected MatchRuleContext getMatchRuleContext() {
		return MatchRuleContext.getMatchRuleContext();
	}

	protected final void splitRun(Consumer<List<SmsSearchResponse>> prepareAction, Predicate<SmsSearchResponse> filter) {
		List<SmsSearchResponse> responses = Lists.newArrayList();

		Integer index = 0;
		List<SmsSearchResponse> subResponses;

		do {
			Integer startIndex = index * HANDLE_RECORD_PER_LOOP;
			Integer tmpEndIndex = ((index + 1) * HANDLE_RECORD_PER_LOOP);
			Integer endIndex = tmpEndIndex > getMatchRuleContext().getResponses().size() ? getMatchRuleContext().getResponses().size() : tmpEndIndex;
			subResponses = getMatchRuleContext().getResponses().subList(startIndex, endIndex);
			prepareAction.accept(subResponses);
			responses.addAll(subResponses.stream().filter(x -> {
				try {
					return filter.test(x);
				} catch (Exception e) {
					return false;
				}
			}).collect(Collectors.toList()));
			index++;
			getMatchRuleContext().clearCache();
		} while (subResponses.size() == HANDLE_RECORD_PER_LOOP);

		getMatchRuleContext().setResponses(responses);
	}

	@Override
	public EvaluateRoot back() {
		return evaluateRoot;
	}
}
